package sysinit

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"os"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"

	// _ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	// _ "github.com/jinzhu/gorm/dialects/sqlite3"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)

// Router gin引擎即路由
var Router *gin.Engine

// GinLoggerConfig gin request日志配置
func GinLoggerConfig() (config gin.LoggerConfig) {
	config.Formatter = func(param gin.LogFormatterParams) string {
		logData := map[string]interface{}{
			"client":        param.ClientIP,
			"time":          param.TimeStamp.Format(time.RFC3339),
			"method":        param.Method,
			"path":          param.Path,
			"protocol":      param.Request.Proto,
			"status":        param.StatusCode,
			"latency":       param.Latency,
			"user_agent":    param.Request.UserAgent(),
			"error_message": param.ErrorMessage,
		}
		jsonBytes, err := json.Marshal(logData)
		if err != nil {
			log.Fatal(err)
		}
		return fmt.Sprintln(string(jsonBytes))
	}
	logFile := Config.GetString("path.log") + "/request.log"
	if fh, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE, 0666); err != nil {
		log.Fatal(err)
	} else {
		config.Output = io.MultiWriter(fh)
	}
	return config
}

// InitRouter 初始化路由
func InitRouter() {
	if Config.GetString("app.env") == "prod" {
		gin.SetMode(gin.ReleaseMode)
	}
	Router = gin.Default()
	Router.Use(gin.LoggerWithConfig(GinLoggerConfig())) //访问日志中间件
	Router.Use(cors.Default())                          // 跨域中间件
	docJSONUrl := fmt.Sprintf("http://localhost:%s/swagger/doc.json", Config.GetString("app.port"))
	Router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, ginSwagger.URL(docJSONUrl))) //swagger文档
}
